import React, { useEffect, useState } from 'react';
import { connect, useDispatch, useSelector } from 'dva';
import { Form, Input, Button } from 'antd';
import Grid from '@/components/Grid';
import Layout from '@/components/Layout';
import Dialog, { withRef } from '@/components/Dialog';
import settings, { getPagination } from '@/settings';
import { check } from '@/services/auth';
import { createAction } from '@/utils';

@Form.create()
@connect(({ auth, loading }) => ({ ...auth, loading }))
@withRef
class ModelForm extends React.Component {
  componentDidMount() {
    const { id, dispatch } = this.props;

    if (id) {
      dispatch(createAction('auth/fetchOne')({
        id
      }));
    }
  }
  handleSubmit = (close, callback) => {
    const { form } = this.props;

    form.validateFields((err, values) => {
      if (!err) {
        callback({
          ...values,
        });
      }
    });
  };
  render() {
    const {
      id,
      data = {},
      form: { getFieldDecorator },
    } = this.props;

    return (
      <Form layout="vertical">
        <Form.Item label="资源url">
          {getFieldDecorator('url', {
            rules: [
              {
                required: true,
                message: '请输入资源url',
              },
            ],
            initialValue: data.url,
          })(<Input placeholder="请输入资源url" />)}
        </Form.Item>
        <Form.Item label="资源名称">
          {getFieldDecorator('name', {
            rules: [
              {
                required: true,
                message: '请输入资源名称',
              },
              {
                validator: async (rule, value, callback) => {
                  if (!value || value.trim() === '') return callback()
                  const data = await check({
                        id,
                        value,
                      })
                  data.valid ? callback() : callback('资源名称已存在');
                },
              },
            ],
            initialValue: data.name,
          })(<Input placeholder="请输入资源名称" />)}
        </Form.Item>
        <Form.Item label="备注">
          {getFieldDecorator('desc', {
            rules: [{ message: '请输入备注信息！', min: 5 }],
            initialValue: data.desc,
          })(<Input.TextArea rows={8} placeholder="请输入至少五个字符" />)}
        </Form.Item>
      </Form>
    );
  }
}

const AuthPage = props => {
  const dispatch = useDispatch()
  const [selectedRows, setSelectedRows] = useState([])
  const { list: { data, total }, params = {} } = useSelector(_ => _.auth)
  const { effects } = useSelector(_ => _.loading)
  const loading = effects['auth/fetchList']

  const columns = [
    {
      title: '资源url',
      dataIndex: 'url',
      width: 200,
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 200
    },
    {
      title: '备注',
      dataIndex: 'desc',
      width: 300
    },
  ];
  useEffect(() => {
    dispatch(createAction('auth/fetchList')());
  }, [dispatch]);

  const handleSelectRows = rows => {
    setSelectedRows(rows)
  };
  const handleAdd = e => {
    dispatch(createAction('auth/reset')());
    Dialog.open({
      title: '新建权限',
      fixed: true,
      component: ModelForm,
      url: 'auth/add',
      onOk: data => {
        handleReload();
      },
    });
  };
  const handleEdit = e => {
    const { id } = selectedRows[0];
    dispatch(createAction('auth/reset')());
    Dialog.open({
      title: '修改权限',
      fixed: true,
      url: 'auth/update',
      data: {
        id,
      },
      options: {
        type: 'put',
      },
      onOk: data => {
        handleReload();
      },
      component: props => <ModelForm {...props} id={id} />,
      connect: ({ loading }) => ({ loading: loading.effects['auth/fetchOne'] }),
    });
  };
  const handleRemove = e => {
    Dialog.confirm({
      title: '确认提示',
      content: '确定要删除已选择的资源？',
      onOk: async () => {
        await dispatch(createAction('auth/delete')({
          id: selectedRows.map(_ => _.id)
        }))
        handleReload();
      },
    });
  };
  const handleGridChange = (oldPagination, sorter) => {
    const pagination = getPagination(oldPagination);
    const payload = {
      ...params,
      ...pagination,
    };

    if (sorter.field) {
      payload.sorter = sorter.field;
      payload.order = sorter.order;
    }

    dispatch(createAction('auth/fetchList')(payload));
  };
  const handleReload = () => {
    dispatch(createAction('auth/fetchList')(params));
  };
  const handleSearch = (value, e) => {
    e.preventDefault();
    const pagination = getPagination({
      pageNumber: 1,
    });
    dispatch(createAction('auth/fetchList')({
      ...params,
      ...pagination,
      name: value,
    }));
  };

  const pageNumber = params[settings.pageNumber];
  return (
    <Layout
      header={{
        icon: 'lock-alt',
        title: '权限管理',
      }}
      toolbar={{
        left: (
          <React.Fragment>
            <Button type="primary" onClick={handleAdd}>
              新建
            </Button>
            <Button onClick={handleEdit} disabled={selectedRows.length !== 1}>
              编辑
            </Button>
            <Button
              type="danger"
              disabled={selectedRows.length === 0}
              onClick={handleRemove}
            >
              删除
            </Button>
          </React.Fragment>
        ),
        right: (
          <Form layout="inline">
            <Input.Search placeholder="请输入要查询的关键词" onSearch={handleSearch} />
          </Form>
        ),
      }}
    >
      <Grid
        selectedRows={selectedRows}
        onSelectRow={handleSelectRows}
        columns={columns}
        data={data}
        loading={loading}
        pagination={{
          pageNumber,
          total,
        }}
        onReload={handleReload}
        onChange={handleGridChange}
      />
    </Layout>
  );
}

export default AuthPage;
